home *** CD-ROM | disk | FTP | other *** search
- Path: fnnews.fnal.gov!kriol
- From: kriol@fnal.gov (Oleg Krivosheev)
- Newsgroups: comp.lang.c++
- Subject: Re: Will it be auto-deleted?
- Date: 27 Feb 1996 00:03:13 GMT
- Organization: FERMILAB, Batavia, IL
- Sender: kriol@martian (Oleg Krivosheev)
- Message-ID: <4gtho1$l4e@fnnews.fnal.gov>
- References: <1996Feb20.110314.46035@yogi.urz.unibas.ch> <4gg91j$gdc@clarknet.clark.net> <4gsff2$21k@news.us.net>
- NNTP-Posting-Host: martian.fnal.gov
- To: thoth256@us.net (Evelio Perez-Albuerne)
-
- Hi,
-
- |> gusty@clark.net (Harlan Messinger) wrote:
- |>
- |> >Song Jin (song@iso.iso.unibas.ch) wrote:
- |> >: I have a question:
- |> >:
- |> >: void myfunction(void)
- |> >: {
- |> >: double *mypointer = new double[100];
- |> >:
- |> >: .....
- |> >:
- |> >: }
- |> >:
- |> >: The mypointer and the buffer it pointed will be auto-deleted after returned
- |> >: from myfunction, am I right?
- |> >:
- |>
- |> >Absolutely not. Any memory allocated with new has to be deleted
- |> >explicitly.
- |>
- |> > delete [] mypointer;
- |>
- |> >Otherwise, once all pointers to it have gone out of scope, it'll just sit
- |> >there unreachable until the heap itself is returned to wherever it came
- |> >from (if that happens) or garbage collection returns it to the heap (if
- |> >your system has garbage collection) or until the machine is rebooted. This
- |> >is called a "memory leak".
- |>
- |> An alternative to manually deleteing the pointer is to use an
- |> auto_array<T> class instead of a plain function pointer. This class is
- |> very similar to the auto_ptr<T> class which I know is being included
- |> in the Standard C++ Library. I don't know if auto_array<T> is also
- |> part of the SC++L, but it is obviously needed since "delete []" not
- |> plain "delete" needs to be called.
- |>
- |> Here is my implementation of auto_array<T>:
- |>
- |> template <class T>
- |> class auto_array
- |> {
- |> public:
- |> auto_array(T* pp = 0) : p(pp) {}
- |> auto_array(auto_array<T>& x) : p(x.p) {x.p = 0;}
- |> ~auto_array() {delete [] p;}
- |>
- |> T& operator [](int i) {return p[i];}
- |> auto_array<T>& operator =(T* pp) {delete [] p; p = pp; return *this;}
-
- great code...
-
- especially when it is used as shown below:
-
- char* pc = new char[10];
- auto_array<char> ac( pc );
-
- ...
-
- ac = pc;
-
- |> auto_array<T>& operator =(auto_array<T>& x)
- |> {delete [] p; p = x.p; x.p = 0; return *this;}
-
- or
-
- ac = ac;
-
- OK
-